package com.zzcy.bt_print_plugin.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.Layout;
import android.util.AttributeSet;
import android.view.View;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.zzcy.bt_print_plugin.R;

/**
 * @author: dhd
 * @date: 2023/12/23
 * Describe : 写点什么解释一下这个类
 */
public class UnderlineTextView extends AppCompatTextView {

    private Paint mPaint;

    public UnderlineTextView(Context context) {
        super(context);
        init();
    }

    public UnderlineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public UnderlineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(ContextCompat.getColor(getContext(),R.color.color_666666));
        mPaint.setStrokeWidth(6); // 下划线的粗细
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
//        int startX = getPaddingLeft();
//        int stopX = getWidth() - getPaddingRight();
//        int baseline = getBaseline();
//        canvas.drawLine(startX, baseline + 5, stopX, baseline + 5, mPaint); // 设置下划线的位置

//        int lineCount = getLineCount(); // 获取总行数
//
//        for (int i = 0; i < lineCount; i++) {
//            int baseline = getLineBounds(i, null); // 获取当前行的基准线位置
//            canvas.drawLine(getPaddingLeft(), baseline + 5, getWidth() - getPaddingRight(), baseline + 5, mPaint);
//        }

        setLayerType(View.LAYER_TYPE_HARDWARE, null); // 设置硬件加速模式
        Layout layout = getLayout();
        int lineCount = layout.getLineCount();

        // 获取字体度量信息
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float baselineOffset = (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;

        for (int i = 0; i < lineCount; i++) {
            int baseline = layout.getLineBaseline(i);
            float startX = getPaddingLeft();
            float stopX = getWidth() - getPaddingRight();
            float startY = baseline + baselineOffset;
            float stopY = startY;
            canvas.drawLine(startX, startY, stopX, stopY, mPaint);
        }


        super.onDraw(canvas);

    }

}
